#!/usr/bin/env python
# -*- coding: utf-8 -*-
# title       :
# author      : jarry

import sys
import os
import logging
from SceneCheckTool.checkScript.CheckBase import CheckBase

try:
    import maya.cmds as cmds
    import pymel.core as pm
    import jarryLibs.mayakit.MayaUtils as mu
    reload(mu)
except:
    pass

logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)


class ELSGroupNameRule(CheckBase):
    def __init__(self):
        super(ELSGroupNameRule, self).__init__()
        pass

    def remap_group_name(self):
        import elsLibs.AssetInfoFromFile as elsaif
        reload(elsaif)
        current_file = cmds.file(query=True, sn=True)
        aif = elsaif.AssetInfoFromFile(current_file)
        self.asset_name = aif.get_name
        self.shortType = aif.get_shortType
        self.step = aif.get_step
        grp_names = []
        grp_key = ["render", "furMesh", "solverCloth", "solverCurves", "deform", "guideCurve", "lowmod"]
        for i in grp_key:
            grp_name = "{0}_{1}_{2}_grp".format(self.shortType, self.asset_name, i)
            grp_names.append(grp_name)
        return grp_names

    def mod_group_name_check(self):
        grp_names = self.remap_group_name()
        mod_grp_name = "mod_grp"
        problem_group = []
        for grp in cmds.listRelatives(mod_grp_name, children=1):
            if grp not in grp_names:
                problem_group.append(grp)
        return problem_group

    def init_file(self):
        import elsLibs.AssetInfoFromFile as elsaif
        reload(elsaif)
        current_file = mu.sceneName()
        aif = elsaif.AssetInfoFromFile(current_file)
        self.asset_name = aif.get_name
        self.shortType = aif.get_shortType
        self.step = aif.get_step

    def check(self):
        current_file = mu.sceneName()
        if not current_file:
            result_log = u'Error: 当前文件未保存!'
            return result_log
        try:
            self.init_file()
        except:
            result_log = u'Error:当前文件不符合ELS项目资产文件命名规则'
            return result_log
        if self.shortType in ['c', 'p']:
            render_mod = 'mod_grp|%s_%s_render_grp' % (self.shortType, self.asset_name)
            if pm.objExists(render_mod):
                result_proc = self.mod_group_name_check()
                if result_proc:
                    result_log = u'Error: 以下次组名称命名错误 :%s\n' % result_proc
                    return result_log
        else:
            if self.step == 'lowmod':
                render_mod = '%s_%s_lowmod_grp' % (self.shortType, self.asset_name)
            else:
                render_mod = '%s_%s_render_grp' % (self.shortType, self.asset_name)

        if not pm.objExists(render_mod):
            result_log = u'Error:不存在这个资产对应的组: %s\n' % render_mod
        else:
            result_log = u'Succeed:没有问题\n'
        return result_log

    def fix(self):
        pass

